package com.entities.projectversion.servlets;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.core.protocols.IKVObject;
import com.core.protocols.IServiceLayerDelegate;
import com.core.servlets.TaskTrackerServlet;
import com.core.utils.GlobalConstants;
import com.core.utils.ListUtils;
import com.entities.projectversion.requestmapparser.ProjectVersionMapParser;
import com.entities.projectversion.servicelayer.ProjectVersionListLayer;
import com.model.project.Version;


public class VersionUpdate
        extends TaskTrackerServlet
        implements IServiceLayerDelegate {

	private Integer             versionId;
	private HttpServletResponse postResponse;

	/**
     * 
     */
	private static final long   serialVersionUID = 1L;



	@Override
	protected void doGet ( HttpServletRequest request,
	                       HttpServletResponse response )
	        throws ServletException, IOException {

		this.versionId = null;
		try {

			this.versionId = Integer.parseInt(request.getParameter(GlobalConstants.SERVLET_PARAM_KEY));

		} catch ( NumberFormatException e ) {
			this.versionId = null;
		}



		super.doGet(request, response);
	}



	@Override
	protected void doPost ( HttpServletRequest request,
	                        HttpServletResponse response )
	        throws ServletException, IOException {

		this.postResponse = response;

		Map <String, String[]> map = request.getParameterMap();
		Version template = ProjectVersionMapParser.fromMap(map);

		ProjectVersionListLayer projectVersionListLayer = new ProjectVersionListLayer();
		projectVersionListLayer.mergeEntityByIDWithTemplate(this.versionId, template, this);
	}



	@Override
	public <T> void responseResponseItemsList ( final List <T> items,
	                                            final Object request,
	                                            final Exception exception ) {

		T item = ListUtils.listItemAtIndex(items, 0);

		this.redirectItemIntoOpenServlet(item);

	}



	private <T> void redirectItemIntoOpenServlet ( T item ) {

		if ( this.postResponse == null ) {
			return;
		}

		String redirection = String.format("%s", GlobalConstants.SERVLET_PROJECTLIST);

		if ( item != null ) {
			if ( item instanceof IKVObject ) {
				IKVObject kvObject = (IKVObject) item;
				String idValue = kvObject.idValue().toString();
				redirection = String.format("%s?%s", GlobalConstants.SERVLET_VERSIONINFO, idValue);
			}
		}

		try {
			this.postResponse.sendRedirect(redirection);
		} catch ( IOException e ) {
			e.printStackTrace();
		}

	}



}
